# @Time    : 2020/9/29 9:03
# @Author  : Del Fung
# @File    : __init__.py.py
# @Software: PyCharm
from configs import config
from utils import *
from base import *
import jmespath
import os

CONFIG = config["default"]  # 获取config配置
data_depot.add_depots(CONFIG.DEPOT_NAMES)  # 新增两个数据仓库用来存储全局变量以及APP信息
data_depot.depot_push("APPINFO", read_yaml(CONFIG.APPINFO_FILE_PATH))  # 将APPINFO存入字典中
data_depot.depot_push('GLOBALS', read_yamls(CONFIG.GLOBAL_VAR_PATH))  # 将全局变量文件夹中的所有yaml文件读取到GLOBAL 字典中
CASES = read_excel(CONFIG.CASE_FILE_NAME)  # 从excel中读取case信息,和测试环境信息
# 环境设置和解析
if CONFIG.ENV == '':
    if 'DEV' in CONFIG.CASE_FILE_NAME.upper():
        CONFIG.ENV = 'DEV'
    elif 'SIT' in CONFIG.CASE_FILE_NAME.upper():
        CONFIG.ENV = 'SIT'
    elif 'UAT' in CONFIG.CASE_FILE_NAME.upper():
        CONFIG.ENV = 'UAT'
    else:
        CONFIG.ENV = 'DEV'
    log.info(f'测试环境：{CONFIG.ENV}')
# 是否进行数据库验证
if CONFIG.IS_DATABASE_VERIFY:
    try:
        dbinfo = data_depot.get('APPINFO', f'{CONFIG.ENV}.Database')
        log.info("正在连接数据库...")
        print("\033[32m正在连接数据库...\033[0m")
        ORA_HAND = sqlhelper(dbinfo)
        log.info("数据库连接成功！")
        print("\033[32m数据库连接成功！\033[0m")
    except Exception as e:
        log.error(e.args)
        print("\033[31m 错误:数据库连接失败！！！\033[0m")
        print("\033[31m 错误:发生严重错误，本次测试中止，请查看日志文件！\033[0m")
        os._exit(0)
# 是否需要认证
if CONFIG.IS_AUTH:  # 是否需要认证
    print("\033[32m正在进行token认证...\033[0m")
    try:
        modules = list(set(jmespath.search(r'[].module', CASES)))
        auth_type = data_depot.get('APPINFO', f'{CONFIG.ENV}.Auth.Type')
        wait_auth_list = list()
        wait_auth_list.append(auth_type)
        for module in modules:
            appcode = data_depot.get('APPINFO', f'{CONFIG.ENV}.{module}.AppCode')
            secret = data_depot.get('APPINFO', f'{CONFIG.ENV}.{module}.Secret')
            wait_auth_list.append([appcode, secret, module])
        url = data_depot.get('APPINFO', f'{CONFIG.ENV}.Auth.Url')
        data = data_depot.get('APPINFO', f'{CONFIG.ENV}.Auth.Data')
        token_auth = Tokens(url, data)  # 实例化token类
        auth_list = token_auth.auth_tokens(wait_auth_list)  # 进行token认证
        for auth in auth_list:
            temp = {"access_token": auth[1]['access_token'],
                    "Authorization": f"{auth[1]['token_type']} {auth[1]['access_token']}"}
            data_depot.update('APPINFO', f'{CONFIG.ENV}.{auth[0]}', temp)
        print("\033[32m成功获取到Token信息！\033[0m")
    except Exception as e:
        log.error(e.args)
        print("\033[31m错误:Token认证，发生严重错误，本次测试中止，请查看日志文件！\033[0m")
        ORA_HAND.close()
        print("\033[32m数据库连接已成功关闭！\033[0m")
        os._exit(0)


# 共享数据
class Cache(object):
    def __init__(self):
        self.cache = dict()

    def get(self, key):
        return self.cache.get(key)

    def set(self, key, value):
        self.cache[key] = value

    def clear_(self):
        self.cache.clear()


cache = Cache()
